package org.jetnuke.servlets.utilities;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;


public class Formatter {
	public String format(Double db,Locale locale){
		try {
			return format(db.doubleValue(),locale);
		} catch (Throwable e) {
		}
		return "";
	}
	public String format(double db,Locale locale){
		DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(locale);
		try {
			fmt.applyPattern("########0.0#");
			return fmt.format(db);
		} catch (Throwable e) {
		}
    	return "";
	}
	
	public String percent(double value,double total,Locale locale){
		DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(locale);
		try {
			fmt.applyPattern("########0.0#");
			double percent=0.;
			if(value!=0 || total!=0){
				percent=value*100./total;
			}
			return fmt.format(percent);
		} catch (Throwable e) {
		}
    	return "";
	}
	public String percent(int value, int total ,Locale locale){
		DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(locale);
		try {
			fmt.applyPattern("########0.0#");
			double percent=0.;
			if(value!=0 || total!=0){
				percent=value*100./total;
			}
			return fmt.format(percent);
		} catch (Throwable e) {
		}
    	return "";
	}
	public String percent(String value_, String total_ ,Locale locale){
		DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(locale);
		try {
			fmt.applyPattern("########0.0#");
			double percent=0.;
			double value=Double.parseDouble(value_);
			double total=Double.parseDouble(total_);
			if(value!=0 || total!=0){
				percent=value*100./total;
			}
			return fmt.format(percent);
		} catch (Throwable e) {
		}
    	return "";
	}
	
	public String format(String db,Locale locale){
    	try {
			return format(Double.parseDouble(db),locale);
		} catch (Throwable e) {
			
		}
		return "";
	}
	public String shorten(String txt, int count){
		if(txt==null)
			return "";
		int length=txt.length();
		if(length<=count)
			return txt;
		return txt.substring(0,count)+"...";
	}
	
}
